package com.hhs.storage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hhs.storage.bean.*;
import com.hhs.storage.dao.NoticeDao;
import com.hhs.storage.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hhs.storage.util.FileUpload;
import com.hhs.storage.util.SysUtil;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hhs
 * @since 2023-04-13
 */
@Service
@Transactional
public class NoticeServiceImpl extends ServiceImpl<NoticeDao, Notice> implements NoticeService {
    @Resource
    private BaseDepartmentService departmentService;
    @Resource
    private BaseDepartmentUserService departmentUserService;
    @Resource
    private BaseRoleService roleService;
    @Resource
    private BaseUserService userService;
    @Resource
    private HttpServletRequest request;
    @Value("${upload.folderName}")
    private String folderName;
    @Override
    public Map<String, Object> getAll(Notice notice, InputParam inputParam) {
        QueryWrapper<Notice> qw = new QueryWrapper<>();
        //根据标题查询
        if (StringUtils.isNotEmpty(notice.getTitle())) {
            qw.like("title", notice.getTitle());
        }
        //根据日期查询
        LocalDate day=inputParam.getStartDate();
        if (day!=null){
            qw.between("create_time",day.atStartOfDay(),LocalDateTime.of(day, LocalTime.MAX));
        }
        //根据部门查询 只传一个部门id
        String departmentId=inputParam.getId();
        if (StringUtils.isNotEmpty(departmentId)){
            //查询当前部门的下属部门
            List<BaseDepartment> childDeparts = departmentService.getChildDeparts(departmentId);
//            String[] ids=departmentIds.split(",");
            List ids = new ArrayList();
            for (BaseDepartment childDepart : childDeparts) {
                ids.add(childDepart.getId());
            }
            //要添加当前部门id
            ids.add(departmentId);
            qw.in("depart_id",ids);
        }else{
            //当前登录用户id
            String loginUserId = SysUtil.getLoginUserId(request);
            //获取自身和上级部门数据
            Map departData=departmentService.getParentDepartsByUserId(loginUserId);
            List<BaseDepartment> myDepartList= (List<BaseDepartment>) departData.get("myDepartList");
            List<BaseDepartment> parentDepartList= (List<BaseDepartment>) departData.get("parentDepartList");
            myDepartList.addAll(parentDepartList);
            Set<String> departIds=new HashSet<>();
            for (int i = 0; i <myDepartList.size() ; i++) {
                departIds.add(myDepartList.get(i).getId());
            }
            qw.in("depart_id", departIds.toArray());
        }

        //判断是否超级管理员
//        Boolean isAdmin=roleService.hasRole(SysUtil.ROLE_FLAG_ADMIN,loginUserId);
//        if (!isAdmin){
//            //非超级管理员添加部门限制
//            List<String> departIds=new ArrayList<>();
//            //登陆用户部门信息
//            BaseDepartmentUser departmentUser = departmentUserService.getByUserId(loginUserId);
//            departIds.add(departmentUser.getDepartId());
//            //所有子部门id
//            List<BaseDepartment> childDeparts=departmentService.getChildDeparts(departmentUser.getDepartId());
//            for (int i = 0; i < childDeparts.size(); i++) {
//                departIds.add(childDeparts.get(i).getId());
//            }
//            qw.in("depart_id", departIds.toArray());
//        }
        qw.orderByDesc("create_time");//按时间倒序排序
        //分页查询
        Page<Notice> result = this.page(new Page<Notice>(
                inputParam.getPage(),
                inputParam.getSize()), qw);
        List<Notice> list = result.getRecords();
        //设置部门和用户信息
        for (int i = 0; i <list.size() ; i++) {
            Notice temp=list.get(i);
            BaseDepartment department=departmentService.getById(temp.getDepartId());
            temp.setDepartment(department);
            BaseUser user=userService.getById(temp.getCreator());
            temp.setUser(user);
        }

        long total = result.getTotal();
        Map map = new HashMap();
        map.put("code", 1);
        map.put("rows", list);
        map.put("total", total);
        return map;
    }
    /**
     * 根据部门id获取当前部门以及上级公告
     * @param departId
     * @param inputParam
     * @return
     */
    @Override
    public Map<String, Object> getNoticeByDepartId(String departId, InputParam inputParam) {
        if(StringUtils.isEmpty(departId)){
            return ResponseInfo.error("数据异常");
        }

        //获取自身和上级部门数据
//        String userId=SysUtil.getLoginUserId(request);
//        Map departData=departmentService.getParentDepartsByUserId(userId);
//        List<BaseDepartment> myDepartList= (List<BaseDepartment>) departData.get("myDepartList");
//        List<BaseDepartment> parentDepartList= (List<BaseDepartment>) departData.get("parentDepartList");
//        myDepartList.addAll(parentDepartList);
//        Set<String> departIds=new HashSet<>();
//        for (int i = 0; i <myDepartList.size() ; i++) {
//            departIds.add(myDepartList.get(i).getId());
//        }
        //创建查询的部门数据
        ArrayList departIds=new ArrayList();
        departIds.add(departId);
        //获取当前部门的上级部门
        BaseDepartment curDepart = departmentService.getById(departId);
        if(StringUtils.isNotEmpty(curDepart.getAncestor())) {
            String[] departArr = curDepart.getAncestor().split(",");
            for (String s : departArr) {
                if (StringUtils.isNotEmpty(s)) {
                    departIds.add(s);
                }
            }
        }
        QueryWrapper<Notice> qw = new QueryWrapper<>();
//        departIds.add(departId);//当前部门
//        //所有子部门id
//        List<BaseDepartment> childDeparts=departmentService.getChildDeparts(departId);
//        for (int i = 0; i < childDeparts.size(); i++) {
//            departIds.add(childDeparts.get(i).getId());
//        }
        qw.in("depart_id", departIds );
        qw.orderByDesc("create_time");//按时间倒序排序
        //分页查询
        Page<Notice> result = this.page(new Page<Notice>(
                inputParam.getPage(),
                inputParam.getSize()), qw);
        List<Notice> list = result.getRecords();
        //设置部门和用户信息
        for (int i = 0; i <list.size() ; i++) {
            Notice temp=list.get(i);
            BaseDepartment department=departmentService.getById(temp.getDepartId());
            temp.setDepartment(department);
            BaseUser user=userService.getById(temp.getCreator());
            temp.setUser(user);
        }
        return ResponseInfo.success(list);
    }

    @Override
    public Map<String, Object> addOrUpdate(Notice notice,String deleImgStr) {
        if (StringUtils.isEmpty(notice.getTitle())) {
            return ResponseInfo.error("标题不可为空");
        }
        if (StringUtils.isEmpty(notice.getContent())) {
            return ResponseInfo.error("内容不可为空");
        }
        //当前登录用户id
        String loginUserId = SysUtil.getLoginUserId(request);
        //判断是否超级管理员
        Boolean isAdmin=roleService.hasRole(SysUtil.ROLE_FLAG_ADMIN,loginUserId);

        if(StringUtils.isNotEmpty(deleImgStr)) {
            //提交时，要删除的图片
            String[] deleArr = deleImgStr.split(",");
            if ( deleArr.length > 0) {
                for (String name : deleArr) {
                    FileUpload.deleteFile(folderName, name);
                }
            }
        }

        if (StringUtils.isEmpty(notice.getId())) {
            BaseDepartmentUser departmentUser = departmentUserService.getByUserId(loginUserId);
            //非超级管理员，权限校验
            if (isAdmin==false){
                if (departmentUser == null) {
                    return ResponseInfo.error("只有部门负责人才可添加公告");
                }
                if (departmentUser.getType() != 1) {
                    return ResponseInfo.error("只有部门负责人才可添加公告");
                }
            }

            //新增
            notice.setId(SysUtil.UUID());
            notice.setCreator(loginUserId);
//            notice.setDepartId(departmentUser.getDepartId());
            notice.setCreateTime(LocalDateTime.now());
            this.save(notice);
            return ResponseInfo.success("新增成功");
        } else {
            //编辑
            BaseDepartmentUser departmentUser = departmentUserService.getByUserId(loginUserId);
            //非超级管理员，权限校验
            if (isAdmin==false){
                if (departmentUser == null) {
                    return ResponseInfo.error("只有部门负责人才可编辑公告");
                }
                if (departmentUser.getType() != 1) {
                    return ResponseInfo.error("只有部门负责人才可编辑公告");
                }
                //判断是否是下级部门的公告
                Notice temp=this.getById(notice.getId());
                //当前公告部门信息
                BaseDepartment department=departmentService.getById(temp.getDepartId());
                String ancestor=department.getAncestor();
                String[] pids=StringUtils.isNotEmpty(ancestor)?ancestor.split(","):new String[0];
                if (!ArrayUtils.contains(pids,departmentUser.getDepartId())&&
                        !departmentUser.getDepartId().equals(department.getId())){
                    return ResponseInfo.error("非相关部门公告不可编辑");
                }

            }
            //更新数据
            UpdateWrapper uw = new UpdateWrapper();
            uw.set("title", notice.getTitle());
            uw.set("content", notice.getContent());
            uw.eq("id", notice.getId());
            this.update(uw);
            return ResponseInfo.success("编辑成功");
        }
    }

    @Override
    public Map<String, Object> dele(String id) {
        //当前登录用户id
        String loginUserId = SysUtil.getLoginUserId(request);
        //判断是否超级管理员
        Boolean isAdmin=roleService.hasRole(SysUtil.ROLE_FLAG_ADMIN,loginUserId);
        if (isAdmin){
            this.removeById(id);
            return ResponseInfo.success("删除成功");
        }
        //非管理员，权限校验
        BaseDepartmentUser departmentUser = departmentUserService.getByUserId(loginUserId);
        if (departmentUser == null) {
            return ResponseInfo.error("只有部门负责人才可删除公告");
        }
        if (departmentUser.getType() != 1) {
            return ResponseInfo.error("只有部门负责人才可删除公告");
        }
        //判断是否是下级部门的公告
        Notice temp=this.getById(id);
        //当前公告部门信息
        BaseDepartment department=departmentService.getById(temp.getDepartId());
        String ancestor=department.getAncestor();
        String[] pids=StringUtils.isNotEmpty(ancestor)?ancestor.split(","):new String[0];
        if (!ArrayUtils.contains(pids,departmentUser.getDepartId())&&
                !departmentUser.getDepartId().equals(department.getId())){
            return ResponseInfo.error("非相关部门公告不可删除");
        }
        this.removeById(id);
        return ResponseInfo.success("删除成功");
    }
}
